Scala Tutorial

Ratings:
(4.5)
Views: 4827
Banner-Img
Share this blog:

Welcome to the Scala Tutorials.  Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003

In addition to free Scala Tutorials, you can find interview questions, how to tutorials and issues and their resolutions of Scala.

Introduction

Scala is a programming language for general software applications. The design of Scala started in 2001, and the first public release was in 2004. The name Scala is a combination of the words “Scalable” and “Language,” which was chosen to indicate its design goal of growing with the demands of the user base. Many of the design decisions of Scala are inspired by perceived shortcomings of the Java language with Scala source code compiling to Java Byte Code, allowing it to run on a Java virtual machine. One of the biggest attractions of Scala is that it has full support for functional programming and has a very strong static type system. This allows for very concise code, requiring fewer lines of code to achieve the same functionality than many other languages, including Java.

Scala Features

Scala is both functional and object-oriented

- every value is an object

- every function is a value--including methods Scala is statically typed

-includes a local type inference system:

in Java 1.5: Pair p = new Pair<Integer, String>(1, "Scala");

in Scala: val p = new MyPair(1, "scala");

Supports lightweight syntax for anonymous functions, higher-order functions, nested functions, currying

ML-style pattern matching

Integration with XML

-Can write XML directly in Scala program

-Can convert XML DTD into Scala class definitions

Support for regular expression patterns

Allows defining new control structures without using macros, and while maintaining static typing

Any function can be used as an infix or postfix operator

Can define methods named +, <= or ::

Scala object system

-Class-based

-Single inheritance

-Can define singleton objects easily

-Subtyping is nominal

-Traits, compound types, and views allow for more flexibility

Scala Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Scala is rich in built-in operators and provides following type of operators:

-Arithmetic Operators

-Relational Operators

-Logical Operators

-Bitwise Operators

-Assignment Operators

Scala Collections

Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).

Basic Data Structures

-Lists

-Sets

-Tuple

-Maps

-Option

Functional Combinators

-map

-foreach

-filter

-zip

-partition

-find

-drop and dropWhile

-foldRight and foldLeft

-flatten

-flatMap

-Generalized functional combinators

-Map

Scala Data Types

Data Type Description
Byte 8 bit signed value. Range from -128 to 127
Short 16 bit signed value. Range -32768 to 32767
Int 32 bit signed value. Range -2147483648 to 2147483647
Long 64 bit signed value. -9223372036854775808 to 9223372036854775807
Float 32 bit IEEE 754 single-precision float
Double 64 bit IEEE 754 double-precision float
Char 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
String A sequence of Chars
Boolean Either the literal true or the literal false
Unit Corresponds to no value
Null null or empty reference
Nothing The subtype of every other type; includes no values
Any The supertype of any type; any object is of type Any
AnyRef The supertype of any reference type

 

Scala Configuration

The separation of configuration from code is a good practice that makes our system customisable as we can load different configurations according to the environment we are running it in. In this article we will describe different approaches to load configurations in Scala and how they can be combined together: loading configurations from a file, from command line parameters or from environment variables.

Configurations from a file

Let’s start with the basic case scenario: given a file, we want to read it and parse its values to use them in our code.

First, we need to define our configuration file, let’s call itapplication.conf.

// application.conf
my {
     secret {
       value = "super-secret"
     }
}
Use the obtained configuration
// config-tutorial.scala
importcom.typesafe.config.ConfigFactory
valvalue =ConfigFactory.load().getString("my.secret.value")
println(s"My secret value is $value")
By default, the ConfigFactory looks for a configuration file called application.conf. If willing to use a different configuration file (e.g.:another.conf), we just need to indicate a different file name and path to load (e.g.: ConfigFactory.load("another")). The Typesafe Config library provides several methods to make sure that the parsed value is compatible with the expected type: have a look at the Config Typesafe Documentation for methods to parse integers, longs, floats, etc.
 

Configurations from command line parameters

Another approach is to allow our users to redefine settings through command line parameters rather than changing the configuration file directly. All we have to do is changing our configuration file as following:
// application.conf
my {
     secret {
       value ="super-secret"
       value =${?VALUE}
     }
}
The output of our script will now change accordingly to the command line parameters provided.
>> scala config-tutorial.scala 
My secret value is super-secret
>> scala config-tutorial.scala -Dmy.secret.value=another-secret
My secret value is another-secret

Configurations from environment variables

Redefining configurations as part of the command line parameters works in most of the cases, but it can be tedious when we have a lot of parameters to change. Also putting sensitive information, such as passwords or tokens, in clear text in a configuration file or a run script may not be safe enough. Another option to load configurations is to inject our parameters from predefined environment variables. In order to achieve this, we can just write a simple method that looks for a specific environment variable before loading the configurations in the previously described approach.
importscala.util.Properties
 defenvOrElseConfig(name:String):String ={
  Properties.envOrElse(
    name.toUpperCase.replaceAll("""\.""", "_"),
      config.getString(name)
      )
}   
Before loading our my.secret.value configuration, this simple method will first check if an environment variable called MY_SECRET_VALUE exists.
Interested in mastering Scala? 
Check out this blog post to learn more Scala Tutorials.
We can now put all together and create a script (gist available here) that will inject configurations in the following order:
From properly named environment variables
From command line parameters
From a configuration file
 
 
/ application.conf
my {
  secret {
   value ="super-secret"
   value =${?VALUE}
  }
}
importcom.typesafe.config.ConfigFactory
importscala.util.Properties
classMyConfig(fileNameOption:Option[String] =None) {
    
  valconfig =fileNameOption.fold(
                  ifEmpty =ConfigFactory.load() )(
                  file => ConfigFactory.load(file) )
  defenvOrElseConfig(name:String):String ={
    Properties.envOrElse(
      name.toUpperCase.replaceAll("""\.""", "_"),
      config.getString(name)
    )
  }
}
The script can be used as following:
valmyConfig =newMyConfig()
valvalue =myConfig.envOrElseConfig("my.secret.value")
println(s"My secret value is $value")

Advantages of Scala

-Scala is ideal for today's scalable, distributed, component-based applications that support concurrency and distribution. -Scala is statically typed that means that the type of some variable is immutable during the whole execution of the program. -There is modular mixin-composition for classes - some hack to enable multiple inheritance in Scala, which solves the diamond problem through linearity of the inheritance hierarchy via traits. -Support of functions that may have other functions as arguments which enables using anonymous functions. -Lower risk to use Scala in an existing Java Application because Scala works seam less with existing Java Code. -high level type system with variance annotations, compound types, lower and upper bounds for types usage of inner and anonymous classes implicit conversions - that means a function take one type as an argument and returns to another type (like converting an Integer into String)

 

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox